import request from "request";
import path from "path";
import clui from "clui";
const { Spinner } = clui;
import inquirer from "inquirer";
import chalk from "chalk";
import fs from "fs";

/**
 * Openapi2 转换为 Openapi3
 *
 * @export
 * @param {*} Json
 * @return {*}
 */
export function Openapi2ToOpenapi3(Json) {
  return new Promise((resolve, reject) => {
    request(
      {
        url: "https://converter.swagger.io/api/convert",
        method: "post",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify(Json),
      },
      function (error, response, body) {
        if (!error && response.statusCode == 200) {
          try {
            var _json = JSON.parse(body);
            resolve(_json);
          } catch (error) {
            resolve(body);
          }
        } else {
          console.log(chalk.red("Api 转换服务器链接失败\n"), chalk.red(error));
        }
      }
    );
  });
}

/**
 * GET 接口请求
 *
 * @param {String} url
 * @return {*}
 */
export const RFile = (url) => {
  var countdown = new Spinner("请稍等...", ["⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"]);
  countdown.start();
  return new Promise((resolve, rejected) => {
    request(
      {
        url: url,
      },
      function (error, response, body) {
        countdown.stop();
        if (!error && response.statusCode == 200) {
          try {
            var _json = JSON.parse(body);
            resolve(_json);
          } catch (error) {
            resolve(body);
          }
        } else {
          console.log(chalk.red("服务器链接失败\n"), chalk.red(error));
        }
      }
    );
  });
};

/**
 * 选择列表
 *
 * @param {Array} pathArray
 * @return {*}
 */
export const PathChoose = (pathArray) => {
  const questions = [
    {
      type: "list",
      name: "_index",
      message: "需要更新的地址",
      choices: pathArray,
      filter: (val) => val,
    },
  ];
  return inquirer.prompt(questions);
};

/**
 * 模块选择事件
 *
 * @param {Array} list
 * @return {*}
 */
export const AskQuestions = (list) => {
  list.unshift("全部");
  const questions = [
    {
      type: "list",
      name: "_index",
      message: "请选择需要更新的模块",
      choices: list,
      filter: (val) => list.indexOf(val),
    },
  ];
  return inquirer.prompt(questions);
};

/**
 * 选择导出位置
 *
 * @param {Array} list
 * @return {*}
 */
export const AskOutPut = (list) => {
  const questions = [
    {
      type: "list",
      name: "_index",
      message: "请选择导出位置",
      choices: list,
      filter: (val) => list.indexOf(val),
    },
  ];
  return inquirer.prompt(questions);
};

/**
 * 获取JSON
 *
 * @param {*} url
 * @return {*}
 */
export const GetJson = async (url) => {
  let reg = /configObject\s+=\s+JSON\.parse\((.+?)\)/;
  let IP = url.split("/")[2];
  const body = await RFile(url);
  let configObject;
  body.replace(reg, function ($i) {
    eval($i);
  });
  let requireArray = [];
  for (let i = 0; i < configObject.urls.length; i++) {
    const element = configObject.urls[i];
    element.url = "http://" + IP + element.url;
    var _name = element.url.split("/")[5];
    if (_name) {
      _name = path.extname(_name).replace(".", "").replace("Controller", "");
    }
    element.key = _name;
    requireArray.push(element);
  }
  return requireArray;
};

export const CheckConfigFile = (config, filePath) => {
  console.log(chalk.greenBright("\nSwagger 接口同步工具\n"));
  if (!config.DocumentPath || !config.DocumentPath instanceof Array || config.DocumentPath.length == 0) {
    console.log(chalk.yellow("请"), chalk.red("配置"), chalk.yellow(` Swagger 文档地址 : ${filePath} -> swagger.`), chalk.red("DocumentPath"));
    return;
  }
  if (typeof config.DocumentPath == "string") {
    console.log(chalk.yellow("现行版本 需要将 path 参数修改为"), chalk.red("数组"));
    console.log(chalk.yellow(`${filePath} ->`));
    console.log(chalk.yellow("------------------------------------------------------------"));
    console.log(chalk.yellow('"path" : ['));
    console.log(chalk.yellow('    "http://192.168.3.84:5005/swagger/frassessment/index.html"'));
    console.log(chalk.yellow("]"));
    console.log(chalk.yellow("------------------------------------------------------------"));
    return;
  }
  if (!config.FolderPath) {
    console.log(chalk.yellow("请"), chalk.red("配置"), chalk.yellow(` Swagger 输出文件夹位置 : ${filePath} -> swagger.`), chalk.red("FolderPath"));
    return;
  }
  var stat = fs.existsSync(path.resolve(config.FolderPath));
  if (!stat) {
    console.log(
      chalk.yellow("请"),
      chalk.red("检查"),
      chalk.yellow(` Swagger 输出文件夹位置 : ${filePath} -> swagger.`),
      chalk.red("FolderPath => 文件夹不存在")
    );
    return;
  }
  return config;
};
